<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndependentPoolTypeController extends BaseController
{

    /**
     * @api {Get} /independentPoolType/typeList 奖池类型列表
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 1,
    "name": "奖池",
    "sort": 1,
    "add_time": "2021-03-24 17:55:44"
    },
    {
    "id": 2,
    "name": "奖池2",
    "sort": 2,
    "add_time": "2021-03-24 17:58:20"
    }
    ]
    }
     */
    public function typeList()
    {
        $list = app('model_independent_pool_type')->orderBy(DB::raw('sort, id'))->get();
        foreach ($list as &$v) {
            $v->add_time = date('Y-m-d H:i:s', $v->add_time);
        }
        return Response::sendData($list);
    }

    /**
     * @api {Post} /independentPoolType/add 添加奖池类型
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} name 名称
     * @apiParam {Int} sort 排序号
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function add(Request $request)
    {
        $name = $request->name;
        $sort = $request->sort;

        $this->paramVerify($name, $sort);

        $res = app('model_independent_pool_type')->insert([
           'name' => $name,
            'sort' => $sort,
            'add_time' => time(),
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @api {Put} /independentPoolType/edit 编辑奖池类型
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} id
     * @apiParam {Int} name 名称
     * @apiParam {Int} sort 排序号
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function edit(Request $request)
    {
        $id = $request->id;
        $name = $request->name;
        $sort = $request->sort;

        $this->paramVerify($name, $sort);
        $type = app('model_independent_pool_type')->where('id', $id)->first();
        if (empty($type)) {
            throw new BasicException(10001);
        }

        $res = app('model_independent_pool_type')->where('id', $id)->update([
            'name' => $name,
            'sort' => $sort,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '编辑失败');
        }
    }

    private function paramVerify($name, $sort)
    {
        if (empty($name)) {
            throw new BasicException(0, '名称不能为空');
        }
        if (mb_strlen($name) > 11) {
            throw new BasicException(0, '名称不能超过11个字符');
        }
        if (empty($sort) || !is_numeric($sort)) {
            throw new BasicException(0, '排序号错误');
        }
    }
}